package cn.edu.ctbu.simplescoremanagementsystem.webapi;

import cn.edu.ctbu.simplescoremanagementsystem.core.PageUtils;
import cn.edu.ctbu.simplescoremanagementsystem.domain.SC;
import cn.edu.ctbu.simplescoremanagementsystem.domain.Student;
import cn.edu.ctbu.simplescoremanagementsystem.service.SCService;
import cn.edu.ctbu.simplescoremanagementsystem.utils.ResultUtils;
import cn.edu.ctbu.simplescoremanagementsystem.vo.Result;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/webapi/sc")
public class SCRestController {
    @Autowired
    SCService scService;
    @PutMapping("/update")
    public Result update(SC sc){
        try{
            SC oldsc = scService.findByID(sc.getId());
            if(StringUtils.isEmpty(sc.getCno())) {
                sc.setCno(oldsc.getCno());
            }
            if(StringUtils.isEmpty(sc.getSno())) {
                sc.setSno(oldsc.getSno());
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return ResultUtils.error(-1,"更新失败,该学生不存在");
        }
        scService.update(sc);
        return ResultUtils.success();
    }

    @GetMapping("/getByPage")
    public Result<PageUtils> getByPage(@RequestParam(value = "page",defaultValue = "0")Integer page,
                                       @RequestParam(value = "size",defaultValue = "7")Integer size,
                                       @RequestParam(value = "cno",defaultValue = "")String cno,
                                       @RequestParam(value = "sno",defaultValue = "")String sno) {
        Sort sort = Sort.by(Sort.Direction.ASC, "id");//排序
        Page<SC> scPage;
        Pageable pageable = PageRequest.of(page, size, sort);
        if (StringUtils.isEmpty(cno) && StringUtils.isEmpty(sno)) {
            scPage = scService.getByPage(pageable);
        } else {
            SC sc = new SC();
            ExampleMatcher matcher = null;
            if (!StringUtils.isEmpty(cno)) {
                sc.setCno(cno);
                matcher = ExampleMatcher.matching()
                        .withMatcher("cname", ExampleMatcher.GenericPropertyMatchers.contains());//模糊查询包含，即%{username}%
            }
            if (!StringUtils.isEmpty(sno)) {
                sc.setCno(sno);
                matcher = ExampleMatcher.matching()
                        .withMatcher("cno", ExampleMatcher.GenericPropertyMatchers.contains());//模糊查询包含，即%{username}%
            }
            Example<SC> example = Example.of(sc,matcher);//模糊查询
            scPage = scService.getByPage(example,pageable);
        }
        PageUtils pageUtils = new PageUtils(scPage.getContent(),scPage.getTotalElements());
        return ResultUtils.success(pageUtils);
    }
}
